package cn.com.wangluotongxin.netty.event;

import cn.com.wangluotongxin.admin.netty.AdminNettyRabbitmqPushService;
import cn.com.wangluotongxin.admin.netty.AdminQueue;
import cn.com.wangluotongxin.admin.netty.constants.AdminNettyMsgType;
import cn.com.wangluotongxin.admin.netty.pojo.LoginRequest;
import cn.com.wangluotongxin.admin.netty.pojo.NotifyResponse;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class LoginEventHandler implements ApplicationListener<LoginEvent> {

    @Autowired
    private AdminNettyRabbitmqPushService rabbitmqPushService;

    @Override
    public void onApplicationEvent(LoginEvent event) {
        if(MapUtil.isEmpty(event.getMessageMap())) return;

        Integer clientId = MapUtil.getInt(event.getMessageMap(), "clientId", -1);
        LoginRequest info = new LoginRequest()
                .setChannelId(event.getChannel().id().asLongText())
                .setClientId(clientId)
                .setDate(DateUtil.date());
        rabbitmqPushService.push(AdminQueue.ADMIN_NETTY_LOGIN, info);

        NotifyResponse response = new NotifyResponse()
                .setChannelId(event.getChannel().id().asLongText())
                .setClientId(clientId)
                .setMsgType(AdminNettyMsgType.LOGIN_RESPONSE)
                .setDateTime(DateUtil.date());
        event.getChannel().writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(response)));
    }
}
